import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../model/difficulty.dart';
import 'game_page.dart';

class LevelSelectPage extends StatefulWidget {
  final Difficulty difficulty;
  const LevelSelectPage({required this.difficulty, super.key});

  @override
  State<LevelSelectPage> createState() => _LevelSelectPageState();
}

class _LevelSelectPageState extends State<LevelSelectPage> {
  SharedPreferences? prefs;

  @override
  void initState() {
    super.initState();
    SharedPreferences.getInstance().then((p) {
      setState(() {
        prefs = p;
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    if (prefs == null) {
      return Scaffold(
        backgroundColor: Theme.of(context).colorScheme.surface,
        body: Center(
          child: CircularProgressIndicator(
            valueColor: AlwaysStoppedAnimation<Color>(
              Theme.of(context).colorScheme.primary,
            ),
          ),
        ),
      );
    }

    return Scaffold(
      extendBody: true, // 让body延伸到底部
      backgroundColor: Colors.transparent, // 设置透明背景
      appBar: AppBar(
        title: Text('${_difficultyText(widget.difficulty)} 关卡选择'),
        // 确保iOS侧滑返回功能正常工作
        automaticallyImplyLeading: true,
      ),
      body: Container(
        decoration: BoxDecoration(
          gradient: LinearGradient(
            begin: Alignment.topCenter,
            end: Alignment.bottomCenter,
            colors: Theme.of(context).brightness == Brightness.dark
                ? [
                    const Color(0xFF121212),
                    const Color(0xFF1E1E1E),
                    const Color(0xFF1E1E1E), // 延伸到底部
                  ]
                : [
                    const Color(0xFFF1F8E9),
                    const Color(0xFFE8F5E8),
                    const Color(0xFFE8F5E8), // 延伸到底部
                  ],
            stops: const [0.0, 0.8, 1.0], // 控制渐变停止点
          ),
        ),
        child: SafeArea(
          bottom: false, // 不在底部添加安全区域，让内容延伸到小白条
          child: Padding(
            padding: const EdgeInsets.fromLTRB(
              16.0,
              16.0,
              16.0,
              0.0,
            ), // 底部不添加padding
            child: GridView.builder(
              physics: const BouncingScrollPhysics(),
              padding: EdgeInsets.only(
                bottom: MediaQuery.of(context).padding.bottom + 16, // 为小白条留出空间
              ),
              gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                crossAxisCount: MediaQuery.of(context).size.width > 600 ? 5 : 3,
                childAspectRatio: 1.2,
                crossAxisSpacing: 12,
                mainAxisSpacing: 12,
              ),
              itemCount: 30,
              itemBuilder: (context, index) {
                final level = index + 1;
                final passed =
                    prefs!.getBool(
                      '${widget.difficulty.name}_${level}_passed',
                    ) ??
                    false;
                final bestTime = prefs!.getInt(
                  '${widget.difficulty.name}_${level}_bestTime',
                );
                final isUnlocked =
                    level == 1 ||
                    (prefs!.getBool(
                          '${widget.difficulty.name}_${level - 1}_passed',
                        ) ??
                        false);

                return _buildLevelCard(
                  context,
                  level,
                  passed,
                  bestTime,
                  isUnlocked,
                );
              },
            ),
          ),
        ),
      ),
    );
  }

  Widget _buildLevelCard(
    BuildContext context,
    int level,
    bool passed,
    int? bestTime,
    bool isUnlocked,
  ) {
    return InkWell(
      borderRadius: BorderRadius.circular(12),
      onTap: isUnlocked
          ? () {
              Navigator.push(
                context,
                MaterialPageRoute(
                  builder: (_) =>
                      GamePage(difficulty: widget.difficulty, level: level),
                ),
              ).then((_) => setState(() {}));
            }
          : null,
      child: Card(
        elevation: 4,
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(12),
          side: BorderSide(
            color: isUnlocked
                ? (passed
                      ? Colors.green
                      : Theme.of(context).colorScheme.primary)
                : Theme.of(context).colorScheme.outline,
            width: 2,
          ),
        ),
        color: isUnlocked
            ? (passed
                  ? (Theme.of(context).brightness == Brightness.dark
                        ? Colors.green.shade800
                        : Colors.green.shade50)
                  : Theme.of(context).colorScheme.primaryContainer)
            : Theme.of(context).colorScheme.surfaceContainerHighest,
        child: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Text(
                '关卡$level',
                style: TextStyle(
                  fontSize: 16,
                  fontWeight: FontWeight.bold,
                  color: isUnlocked
                      ? Theme.of(context).colorScheme.onSurface
                      : Theme.of(context).colorScheme.onSurface.withAlpha(128),
                ),
              ),
              const SizedBox(height: 4),
              if (!isUnlocked) ...[
                Icon(
                  Icons.lock,
                  color: Theme.of(context).colorScheme.onSurface.withAlpha(128),
                  size: 20,
                ),
              ] else if (passed) ...[
                Icon(Icons.check_circle, color: Colors.green, size: 20),
                if (bestTime != null)
                  Text(
                    '最佳:${_formatTime(bestTime)}',
                    style: TextStyle(
                      fontSize: 12,
                      color: Theme.of(context).brightness == Brightness.dark
                          ? Colors.green.shade200
                          : Theme.of(
                              context,
                            ).colorScheme.onSurface.withAlpha(179),
                    ),
                  ),
              ] else ...[
                Icon(
                  Icons.play_arrow,
                  color: Theme.of(context).colorScheme.primary,
                  size: 20,
                ),
              ],
            ],
          ),
        ),
      ),
    );
  }

  String _formatTime(int seconds) {
    int minutes = seconds ~/ 60;
    int remainingSeconds = seconds % 60;
    return '$minutes:${remainingSeconds.toString().padLeft(2, '0')}';
  }

  String _difficultyText(Difficulty d) {
    switch (d) {
      case Difficulty.easy:
        return '炼气期';
      case Difficulty.medium:
        return '筑基期';
      case Difficulty.hard:
        return '结丹期';
      case Difficulty.high:
        return '元婴期';
      case Difficulty.superHigh:
        return '化神期';
    }
  }
}
